﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using FxSuperCore.Log;
using FxSuperCore.Utils;
using FxWinSuper.Functions;
using FxWinSuper.Plugin;
using FxWinSuper.Plugin.Data;
using FxWinSuper.UI.Menu.Controls;
using FxWinSupper.Config;
using HandyControl.Controls;
using MessageBox = System.Windows.MessageBox;
using TextBox = System.Windows.Controls.TextBox;

namespace FxWinSuper.UI.Menu.Pages
{
	/// <summary>
	/// PluginPage.xaml 的交互逻辑
	/// </summary>
	internal partial class PluginPage : Page
	{
		private bool _isLoadedLocalPlugin;
		private int _curTabIndex = 0;

		public ILogPrint Logger => InternalLog.Instance;

		public PluginPageViewModel ViewModel => DataContext as PluginPageViewModel;

		public string SelectedLocalPluginName
		{
			get
			{
				object selectedItem = uiDataGrid?.SelectedItem;
				if (selectedItem == null)
				{
					return string.Empty;
				}

				if (selectedItem is LocalPluginEntity pluginEntity)
				{
					return pluginEntity.PluginName;
				}
				return string.Empty;
			}
		}

		public RemotePluginEntity SelectedRemotePluginName
		{
			get
			{
				object selectedItem = uiRemoteDataGrid?.SelectedItem;
				if (selectedItem == null)
				{
					return null;
				}

				if (selectedItem is RemotePluginEntity pluginEntity)
				{
					return pluginEntity;
				}

				return null;
			}
		}

		public bool CurPageIsLocalPlugin => uiTabPage.SelectedIndex == 0;

		public PluginPage()
		{
			InitializeComponent();
			_curTabIndex = uiTabPage.SelectedIndex;
			Loaded += PluginPage_Loaded;
			uiTabPage.SelectionChanged += UiTabPage_SelectionChanged;
		}

		private void PluginPage_Loaded(object sender, RoutedEventArgs e)
		{
			// 加载本地插件
			if (!_isLoadedLocalPlugin)
			{
				RefreshLoadLocalPlugin();
				_isLoadedLocalPlugin = true;
			}
		}

		private void UiTabPage_SelectionChanged(object sender, SelectionChangedEventArgs e)
		{
			if (_curTabIndex == uiTabPage.SelectedIndex)
			{
				return;
			}

			_curTabIndex = uiTabPage.SelectedIndex;
			if (CurPageIsLocalPlugin)
			{
				RefreshLoadLocalPlugin();
			}
			else
			{
				RefreshLoadRemotePlugin();
			}
		}

		private void RefreshLoadLocalPlugin()
		{
			uiSearchPluginName.Text = "";
			ViewModel.LocalPluginEntities.Clear();
			PluginController.GetLocalPlugins()
				.ForEach(ViewModel.LocalPluginEntities.Add);
		}

		private async void RefreshLoadRemotePlugin()
		{
			if (!ViewModel.HasPluginStore)
			{
				return;
			}

			try
			{
				uiSearchRemotePluginName.Text = "";
				List<RemotePluginEntity> remotePluginEntities = await ViewModel.PluginStore.GetAllPlugins();
				ViewModel.RemotePluginEntities.Clear();
				remotePluginEntities.ForEach(ViewModel.RemotePluginEntities.Add);
			}
			catch (Exception e)
			{
				Logger.Error($"从插件商店获取插件信息失败: {e.Message}");
				MessageBox.Show("从插件商店获取插件信息失败", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
			}
		}

		private void LocalPluginSearchPluginKeyDownEvent(object sender, KeyEventArgs e)
		{
			if (e.Key != Key.Enter)
			{
				return;
			}

			PluginPageViewModel pluginPageViewModel = ViewModel;
			TextBox tbx = sender as TextBox;
			pluginPageViewModel.LocalPluginEntities.Clear();
			PluginController.GetLocalPlugins()
				.Where(plugin => plugin.PluginName.ToLower().Contains(tbx.Text.ToLower()))
				.ToList()
				.ForEach(pluginPageViewModel.LocalPluginEntities.Add);
		}

		// 禁用/启用插件
		private void DisableButtonClickEvent(object sender, RoutedEventArgs e)
		{
			PluginController.ChangePluginDisableStatus(SelectedLocalPluginName);
		}

		// 卸载插件
		private void UninstallButtonClickEvent(object sender, RoutedEventArgs e)
		{
			PluginController.UninstallPlugin(SelectedLocalPluginName);
		}

		// 搜索远程插件
		private async void RemotePluginSearchPluginKeyDownEvent(object sender, KeyEventArgs e)
		{
			if (e.Key != Key.Enter)
			{
				return;
			}
			TextBox tbx = sender as TextBox;
			try
			{
				List<RemotePluginEntity> remotePluginEntities = await ViewModel.PluginStore.SearchPlugin(tbx.Text);
				ViewModel.RemotePluginEntities.Clear();
				remotePluginEntities.ForEach(ViewModel.RemotePluginEntities.Add);
			}
			catch (Exception excep)
			{
				Logger.Error($"从插件商店搜索插件信息失败,keyword:[{tbx.Text}],detail:{excep.Message}");
				MessageBox.Show("搜索插件信息", "提示", MessageBoxButton.OK, MessageBoxImage.Error);
			}
		}

		// 下载插件
		private void DownloadButtonClickEvent(object sender, RoutedEventArgs e)
		{
			RemotePluginEntity remotePlugin = SelectedRemotePluginName;
			if (remotePlugin == null)
			{
				return;
			}

			if (remotePlugin.DependencySoftwareVersionCode > Conf.VersionCode)
			{
				CommonUtils.ShowWarningMsgAsync("当前软件版本小于该插件的依赖版本，无法安装");
				return;
			}

			string pluginName = remotePlugin.PluginName;
			LocalPluginEntity localPlugin = PluginController.GetLocalPlugin(pluginName);
			if (localPlugin != null && localPlugin.VersionCode >= remotePlugin.VersionCode)
			{
				var res = MessageBox.Show("本地插件的版本高于商店中该插件的版本，是否要继续安装", "提示",
					MessageBoxButton.OKCancel, MessageBoxImage.Information);
				if (res == MessageBoxResult.Cancel)
				{
					return;
				}
			}

			string pluginZipPath = PluginController.GeneratePluginPackagePath(pluginName);
			if (File.Exists(pluginZipPath))
			{
				File.Delete(pluginZipPath);
			}

			DownloadView downloadView = new DownloadView()
			{
				Width = 500,
				NeedConfirm = true,
				Title = localPlugin == null ? $"您确定要安装插件:[{pluginName}]吗？" : $"您已经安装[{pluginName}]插件，继续操作将会自动重启并删除已安装的插件，是否继续？"
			};
			Dialog dialog = null;
			downloadView.OnConfirmEvent += async (o, args) =>
			{
				downloadView.Title = "正在下载插件，请稍等，下载完成后将自动安装";
				try
				{
					bool res = await ViewModel.PluginStore.DownloadPlugin(pluginName, pluginZipPath, progress =>
					{
						if (progress >= 0 && progress <= 100)
						{
							Dispatcher.Invoke(() => downloadView.Value = progress);
						}
					});
					if (!res)
					{
						Logger.Error($"下载插件[{pluginName}]失败");
						dialog?.Close();
						MessageBox.Show("下载插件失败，您可通过日志查看失败详情", "提示", MessageBoxButton.OK, MessageBoxImage.Error);
					}

					if (!File.Exists(pluginZipPath))
					{
						throw new FileNotFoundException($"未找到下载完成的插件包，插件名：[{pluginName}]", pluginZipPath);
					}

					downloadView.Title = "插件包下载成功，即将进行安装";
				}
				catch (Exception exception)
				{
					Logger.Error($"下载插件[{pluginName}]出现异常:{exception.Message}, {exception.StackTrace}");
					MessageBox.Show("下载插件失败，您可通过日志查看失败详情", "提示", MessageBoxButton.OK, MessageBoxImage.Error);
					dialog?.Close();
					return;
				}
				// 进行插件安装
				await Task.Delay(500);
				PluginController.InstallPlugin(pluginName);
				dialog?.Close();
			};
			dialog = Dialog.Show(downloadView);
		}

		// 刷新插件商店
		private void RefreshRemotePlugin(object sender, RoutedEventArgs e)
		{
			RefreshLoadRemotePlugin();
		}
	}
}
